﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Painting;
using Mvvm.Models;
using SkiaSharp;

namespace Mvvm.Services
{
    public class EmotionTrajectoryService : IEmotionTrajectoryService
    {
        public async Task<(ISeries[] Series, Axis[] XAxes, Axis[] YAxes, ISeries[] EmotionPieSeries, ISeries[] EmotionTonePieSeries)> GenerateEmotionTrajectoryData(List<ChatData> chatDataList)
        {
            var xIndices = Enumerable.Range(0, chatDataList.Count).ToList();

            // 创建折线图系列，展示情感分数随时间的变化
            var lineSeries = new LineSeries<ObservablePoint>
            {
                Values = new ObservableCollection<ObservablePoint>(chatDataList.Zip(xIndices, (chatData, index) =>
                    new ObservablePoint(index, chatData.EmotionScore))),
                Name = "情感轨迹",
                Fill = null,
                LineSmoothness = 0.3, // 可调整线条平滑度
                GeometrySize = 0, // 数据点标记大小

            };

            ISeries[] series = new ISeries[] { lineSeries };

            // 设置X轴（时间轴）相关属性
            Axis[] xAxes = new Axis[]
            {
                new Axis
                {
                    Name = "时间",
                    NamePaint = new SolidColorPaint(SKColors.Black),
                    LabelsPaint = new SolidColorPaint(SKColors.Black),
                    TextSize = 12,
                    Labels = chatDataList.Select(x => x.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")).ToArray(),
                    // 设置X轴的最小和最大范围，以确保索引范围匹配
                    MinLimit = -0.5,
                    MaxLimit = chatDataList.Count - 0.5
                }
            };

            // 设置Y轴（情感分数轴）相关属性
            Axis[] yAxes = new Axis[]
            {
                new Axis
                {
                    Name = "情感分数",
                    NamePaint = new SolidColorPaint(SKColors.Black),
                    LabelsPaint = new SolidColorPaint(SKColors.Black),
                    TextSize = 12,
                    MinLimit = 0,
                    MaxLimit = 1
                }
            };

            // 统计不同情感Emotion的占比（这里假设Emotion有几种预定义的分类，示例可根据实际情况调整）
            var emotionGroups = chatDataList.GroupBy(x => x.Emotion).ToDictionary(g => g.Key, g => g.Count());
            var emotionPieSeries = new List<PieSeries<double>>();
            foreach (var emotion in emotionGroups.Keys)
            {
                var values = new ObservableCollection<double>();
                values.Add(emotionGroups[emotion]);
                emotionPieSeries.Add(new PieSeries<double>
                {
                    Values = values,
                    Name = emotion,
                    Fill = GetColorForEmotion(emotion), // 根据情感获取对应的颜色（需实现此方法，见下方示例）
                    Stroke = null,
                    DataLabelsPaint = new SolidColorPaint(SKColors.Black),
                    DataLabelsSize = 12,
                    DataLabelsPosition = LiveChartsCore.Measure.PolarLabelsPosition.Middle,
                    DataLabelsFormatter = point =>
                    {
                        double value = point.Coordinate.PrimaryValue;
                        string percentage = ((value / chatDataList.Count) * 100).ToString("F2");
                        return $"{point.Context.Series.Name}: {value} ({percentage}%)";
                    },
                    AnimationsSpeed = TimeSpan.FromSeconds(0.5),
                    EasingFunction = LiveChartsCore.EasingFunctions.Lineal
                });
            }

            // 统计不同情绪EmotionTone的占比（同样假设EmotionTone有几种预定义的分类，可按实际调整）
            var emotionToneGroups = chatDataList.GroupBy(x => x.EmotionTone).ToDictionary(g => g.Key, g => g.Count());
            var emotionTonePieSeries = new List<PieSeries<double>>();
            foreach (var emotionTone in emotionToneGroups.Keys)
            {
                var values = new ObservableCollection<double>();
                values.Add(emotionToneGroups[emotionTone]);
                emotionTonePieSeries.Add(new PieSeries<double>
                {
                    Values = values,
                    Name = emotionTone,
                    Fill = GetColorForEmotionTone(emotionTone),
                    Stroke = null,
                    DataLabelsPaint = new SolidColorPaint(SKColors.Black),
                    DataLabelsSize = 12,
                    DataLabelsPosition = LiveChartsCore.Measure.PolarLabelsPosition.Middle,
                    DataLabelsFormatter = point =>
                    {
                        double value = point.Coordinate.PrimaryValue;
                        string percentage = ((value / chatDataList.Count) * 100).ToString("F2");
                        string chineseName = EmotionToneColorMap.TryGetValue(point.Context.Series.Name.ToLower(), out var info)? info.ChineseName : "其他";
                        return $"{chineseName}: {value} ({percentage}%)";
                    },
                    AnimationsSpeed = TimeSpan.FromSeconds(0.5),
                    EasingFunction = LiveChartsCore.EasingFunctions.Lineal
                });
            }

            return (series, xAxes, yAxes, emotionPieSeries.ToArray(), emotionTonePieSeries.ToArray());
        }

        // 示例方法，根据情感获取对应的颜色，可根据实际设计调整颜色映射逻辑
        private SolidColorPaint GetColorForEmotion(string emotion)
        {
            switch (emotion)
            {
                case "快乐":
                    return new SolidColorPaint(SKColors.Yellow);
                case "悲伤":
                    return new SolidColorPaint(SKColors.Gray);
                case "愤怒":
                    return new SolidColorPaint(SKColors.Red);
                // 其他情感对应的颜色映射...
                default:
                    return new SolidColorPaint(SKColors.Blue);
            }
        }

        // 示例方法，根据情绪获取对应的颜色，同样可根据实际设计调整
        private static readonly Dictionary<string, (SKColor Color, string ChineseName)> EmotionToneColorMap = new Dictionary<string, (SKColor Color, string ChineseName)>
        {
            { "angry", (SKColors.Red, "愤怒") },
            { "sad", (SKColors.DarkGray, "悲伤") },
            { "like", (SKColors.Pink, "喜欢") },
            { "disgusting", (SKColors.Orange, "厌恶") },
            { "fearful", (SKColors.Purple, "恐惧") },
            { "happy", (SKColors.Yellow, "开心") },
            { "normal", (SKColors.LightGray, "中性") },
            { "其他", (SKColors.Blue, "其他") }
        };

        private SolidColorPaint GetColorForEmotionTone(string emotionTone)
        {
            if (EmotionToneColorMap.TryGetValue(emotionTone.ToLower(), out var colorInfo))
            {
                return new SolidColorPaint(colorInfo.Color);
            }
            return new SolidColorPaint(EmotionToneColorMap["其他"].Color);
        }
    }
}